package org.quickjsf.jsf.component;

import java.util.List;
import java.util.Map;

import javax.faces.component.FacesComponent;
import javax.faces.component.html.HtmlOutputFormat;

import org.quickjsf.common.Constants.BOOLEAN_OP;
import org.quickjsf.core.base.viewmodel.vo.ColumnModel;
import org.quickjsf.core.datamodel.OptionType;


@FacesComponent(ColumnOutputFormat.COMPONENT_TYPE)
public class ColumnOutputFormat extends HtmlOutputFormat{
	
	public static final String COMPONENT_TYPE = "org.quickjsf.jsf.component.ColumnOutputFormat";
	
    private enum PropertyKeys {
    	column,
    	optionType;
    }
    
    @Override
    public Object getValue() {
    	Object value = super.getValue();
//    	return value;
    	if (value == null) {
    		return null;
    	}
    	return getColumnOptionTypeToValue(value);
    }
    
    @SuppressWarnings("unchecked")
	private Object getColumnOptionTypeToValue(Object value) {
		if (!getColumn().getFormat()) {
			if (value instanceof Boolean) {
				return value.equals(Boolean.TRUE) ? BOOLEAN_OP.TRUE : BOOLEAN_OP.FALSE;
 			}
    		return value;
    	} else {
    		Map<String, List<OptionType>> optionTypes = (Map<String, List<OptionType>>) getOptionType();
    		if (optionTypes == null) {
    			return null;
    		}
    		try {
    			for (OptionType optionType : optionTypes.get(getColumn().getProperty())) {
    				if (value.equals(optionType.getValue())) {
    					return optionType.getName();
    				}
				}
    			return null;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
    	}
    }
    
	public Object getOptionType() {
		return getStateHelper().eval(PropertyKeys.optionType);
	}

	public void setOptionType(Object optionType) {
		getStateHelper().put(PropertyKeys.optionType, optionType);
	}

	public ColumnModel getColumn() {
		return (ColumnModel) getStateHelper().eval(PropertyKeys.column);
	}

	public void setColumn(ColumnModel column) {
		getStateHelper().put(PropertyKeys.column, column);
	}
}
